package com.dukla.picbak.handler;

import com.dukla.picbak.utils.MinioUtil;
import com.dukla.picbak.vo.MediaFileInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;

import javax.annotation.PostConstruct;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

@Component
public class FileSaver {

    private final Logger logger =
            LoggerFactory.getLogger(FileSaver.class);

    @Autowired
    private MinioUtil minioUtil;

    @Value("${minio.bucket-name}")
    private String bucketName;


    @Value("${pic-backup.thread-count}")
    int threadCount;

    @Autowired
    DataContainer dataContainer;

    private static boolean bucketChecked = false;

    @PostConstruct
    private void init(){
        for(int i = 0; i < threadCount; i++){
            String name = "SaveThread-"+i;
            logger.info("start Save thread:{}",name);
            new Thread(new SaveThread(name)).start();
        }
    }

    /**
     * 检查桶
     */
    private void checkBucket(){
        if(!bucketChecked){
            if(!minioUtil.existsBucket(bucketName)){
                minioUtil.createBucket(bucketName);
            }
            bucketChecked = true;
        }
    }

    /**
     * 保持到Minio
     */
    private void saveToMinio(MediaFileInfo picFile){
        //执行一次检查桶
        this.checkBucket();

        String dir = new SimpleDateFormat("yyyy/MM/dd/").format(picFile.getMediaDate());
        String objectName = dir + picFile.getFile().getName();
        try {
            Map<String,String> tags = new HashMap<>();
            String path = picFile.getFile().getAbsolutePath().replace("\\","/");
            //扩展名
            tags.put("type",path.substring(path.lastIndexOf(".")+1));
            int start = path.indexOf("/");
            int end = path.lastIndexOf("/");
            //路径替换为空格
            String sub = path.substring(start+1,end).replace("/"," ");
            tags.put("info",sub);
            minioUtil.saveInputStreamObjectWithTag(bucketName,objectName,new BufferedInputStream(new FileInputStream(picFile.getFile())),tags);
        } catch (FileNotFoundException e) {
            logger.error(e.getMessage(),e);
        }
    }

    /**
     * 数据处理线程
     */
    private class SaveThread implements Runnable{

        private String name;

        public SaveThread(String name){
            this.name = name;
        }

        @Override
        public void run() {
            while (true) {
                try {
                    MediaFileInfo picFile = dataContainer.takeFileContentQueue();
                    saveToMinio(picFile);
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }

    }


}
